/*
 * CanonicalIterator.java
 *
 * Created on Jun 4, 2007, 11:25:33 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.infomancers.collections.iterators;

import java.util.Iterator;

/**
 *
 * @author aviadbd
 */
public class CanonicalIterator<T, K> implements Iterator<T> {
    
    public static interface Canonise<T, K> {
        Iterable<T> canonise(K item);
    }
    
    private Iterator<T> subItems;
    private Iterator<K> items;
    private Canonise<T, K> canoniser;
    
    public CanonicalIterator(Iterable<K> itemsList, Canonise<T, K> canoniser) {
        items = itemsList.iterator();
        this.canoniser = canoniser;
        if (items.hasNext()) {
            subItems = canoniser.canonise(items.next()).iterator();
        }
    }
    
    public boolean hasNext() {
        return subItems != null && subItems.hasNext();
    }
    
    public T next() {
        T result = subItems.next();
        
        if (!subItems.hasNext()) {
            subItems = items.hasNext() ? canoniser.canonise(items.next()).iterator() : null;
        }
        
        return result;
    }
    
    public void remove() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
